//index.js
//获取应用实例
const app = getApp()
const questionService = require('../../service/question.js');

Page({
  data: {
    title:"问答",
    activeTab:1,
    hotList:{
      list:[],
      page:1,
      num:10,
      isLast:false,
      type:0
    },
    newList:{
      list: [],
      page: 1,
      num: 10,
      isLast: false,
      type: 1
    },
    waitList:{
      list: [],
      page: 1,
      num: 10,
      isLast: false,
      type: 2
    },
    isShowBackTop:false
  },
  onLoad: function () {
    this.getCurrentTabList();
  },
  getContentList(d,fn) {
    questionService.getQuestionList(d).then(res => {
      if (res.resCode == 0) {
        fn(res.object);
      }
    })
  },
  onReachBottom() {
    this.getCurrentTabList();
  },
  getCurrentTabList(){
    const tabFactory = {
      1:"hotList",
      2:"newList",
      3:"waitList"
    }
    let config = this.data[tabFactory[this.data.activeTab]];
    if(config.isLast) return false;
    let d = {
      num:config.num,
      page:config.page,
      type:config.type
    }
    this.getContentList(d,(data)=>{
      if(!data.length){
        let lastKey = this.getCurrentValueByKey(tabFactory, "isLast");
        this.setData({
          lastKey:true
        });
        return false;
      };
      let pageKey = this.getCurrentValueByKey(tabFactory,"page");
      let listKey = this.getCurrentValueByKey(tabFactory, "list");
      console.log(pageKey,listKey);
      this.setData({
        [pageKey]: config.page+1,
        [listKey]:config.list.concat(data)
      });
      console.log(this.data);
    })
  },
  getCurrentValueByKey(tabFactory,key){
    return `${tabFactory[this.data.activeTab]}.${key}`
  },
  switchTab(e){
    let data = e.currentTarget.dataset;
    const tabFactory = {
      1: "hotList",
      2: "newList",
      3: "waitList"
    }
    this.setData({
      activeTab: data.tab
    });
    if (this.data[tabFactory[data.tab]].list.length) return false;
    this.getCurrentTabList();
  },
  onPageScroll:function(e){
    let deviceInfo = app.globalData.deviceInfo;
    if (e.scrollTop > deviceInfo.screenHeight +50){
      this.setData({
        isShowBackTop:true
      })
    }else{
      this.setData({
        isShowBackTop:false
      })
    }
  }
})
